﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace MVC3DEMO.Controllers
{
    public class MediaController : Controller
    {
        public MediaController()
        {
        }

        public UploadReturn UploadPicture(System.Web.HttpRequestBase request, System.Web.HttpServerUtilityBase server, string imagePath, string thumbPath, int sizeWidthThumbs, int sizeHeightThumbs)
        {
            if (request.Files != null)
            {
                var posted = request.Files["uploadFile"];
                if (posted.FileName != "")
                {
                    if (posted.ContentLength < 4201678)
                    {
                        if (posted.ContentType == "image/jpeg" || posted.ContentType == "image/jpg"
                            || posted.ContentType == "image/pjpeg" || posted.ContentType == "image/pjpg"
                            || posted.ContentType == "image/gif" || posted.ContentType == "image/png")
                        {
                            if (!Directory.Exists(server.MapPath(imagePath)))
                            {

                                Directory.CreateDirectory(server.MapPath(imagePath));
                            }
                            var imageName = Path.GetFileName(posted.FileName);
                            var nameInImageFolder = CheckFileName(server, imageName, imagePath);
                            var nameInThumbFolder = CheckFileName(server, nameInImageFolder, thumbPath);
                            while (nameInImageFolder != nameInThumbFolder)
                            {
                                nameInImageFolder = CheckFileName(server, nameInThumbFolder, imagePath);
                                nameInThumbFolder = CheckFileName(server, nameInImageFolder, thumbPath);
                            }
                            imageName = nameInImageFolder;

                            var filePath = imagePath + "/" + imageName;
                            posted.SaveAs(server.MapPath(filePath));

                            var newImage = new Bitmap(server.MapPath(filePath));
                            if (!Directory.Exists(server.MapPath(thumbPath)))
                            {
                                Directory.CreateDirectory(server.MapPath(thumbPath));
                            }
                            filePath = thumbPath + "/" + imageName;

                            var index = GetIndex(newImage.Width, newImage.Height, sizeWidthThumbs, sizeHeightThumbs);
                            var sizeWidthToClip = index == 0 ? newImage.Width : sizeWidthThumbs * index;
                            var sizeHeightToClip = index == 0 ? newImage.Height : sizeHeightThumbs * index;
                            var chunkBounds = new Rectangle(GetFirstPixcelToClip(newImage.Width, sizeWidthToClip), GetFirstPixcelToClip(newImage.Height, sizeHeightToClip), sizeWidthToClip, sizeHeightToClip);
                            Bitmap chunk = newImage.Clone(chunkBounds, newImage.PixelFormat);
                           // chunk.Save(server.MapPath(filePath), ImageFormat.Jpeg);
                            int sizeWithThumb = sizeWidthToClip > sizeWidthThumbs ? sizeWidthThumbs : sizeWidthToClip;
                            int sizeHeightThumb = sizeHeightToClip > sizeHeightThumbs ? sizeHeightThumbs : sizeHeightToClip;
                            Image myThumbnail = chunk.GetThumbnailImage(sizeWithThumb, sizeHeightThumb, null, IntPtr.Zero);
                           // myThumbnail.Save(server.MapPath(filePath));

                            newImage.Dispose();
                            myThumbnail.Dispose();
                            chunk.Dispose();
                            return (new UploadReturn(1, filePath));
                        }
                        else
                        {
                            return (new UploadReturn(2, "Type of file isn't support!Please try another!"));
                        }
                    }
                    else
                    {
                        return (new UploadReturn(3, "ContentLength of File too lagre,please resize picture!"));
                    }
                }
                else
                {
                    return (new UploadReturn(4, "You has not been upload a file!.Please try again!"));
                }

            }

            return (new UploadReturn(5, "You has not been upload a file!.Please try again!"));
        }

        private int GetIndex(int width, int height, int widthThumb, int heightThumb)
        {
            int index = 0;
            if (width < height)
            {
                index = 0;
                while (index * widthThumb < width)
                {
                    index++;
                }
                index--;
                while (index * heightThumb > height)
                {
                    index--;
                }
                return index;
            }
            while (index * heightThumb < height)
            {
                index++;
            }
            index--;
            while (index * widthThumb > width)
            {
                index--;
            }
            return index;
        }

        private int GetFirstPixcelToClip(int size, int thumbSize)
        {
            var length = size - thumbSize;
            return length / 2;
        }

        public UploadReturn UploadImage(System.Web.HttpRequestBase request, System.Web.HttpServerUtilityBase server, string folderPath)
        {
            if (request.Files != null)
            {
                var posted = request.Files["uploadFile"];
                if (posted.FileName != "")
                {
                    if (posted.ContentLength < 4201678)
                    {
                        if (posted.ContentType == "image/jpeg" || posted.ContentType == "image/jpg"
                            || posted.ContentType == "image/pjpeg" || posted.ContentType == "image/pjpg"
                            || posted.ContentType == "image/gif" || posted.ContentType == "image/png")
                        {
                            if (!Directory.Exists(server.MapPath(folderPath)))
                            {
                                Directory.CreateDirectory(server.MapPath(folderPath));
                            }
                            var imageName = Path.GetFileName(posted.FileName);
                            imageName = CheckFileName(server, imageName, folderPath);
                            var filePath = folderPath + "/" + imageName;

                            posted.SaveAs(server.MapPath(filePath));
                            return (new UploadReturn(1, filePath));
                        }
                        else
                        {
                            return (new UploadReturn(2, "Type of file isn't support!Please try another!"));
                        }
                    }
                    else
                    {
                        return (new UploadReturn(3, "ContentLength of File too lagre,please resize picture!"));
                    }
                }
                else
                {
                    return (new UploadReturn(4, "You has not been upload a file!.Please try again!"));
                }

            }

            return (new UploadReturn(5, "You has not been upload a file!.Please try again!"));
        }

        public UploadReturn UploadThumb(System.Web.HttpRequestBase request, System.Web.HttpServerUtilityBase server, string folderPath)
        {
            if (request.Files != null)
            {
                var posted = request.Files["uploadFile"];
                if (posted.FileName != "")
                {
                    if (posted.ContentLength < 4201678)
                    {
                        if (posted.ContentType == "image/jpeg" || posted.ContentType == "image/jpg"
                            || posted.ContentType == "image/pjpeg" || posted.ContentType == "image/pjpg"
                            || posted.ContentType == "image/gif" || posted.ContentType == "image/png")
                        {
                            if (!Directory.Exists(server.MapPath(folderPath)))
                            {
                                Directory.CreateDirectory(server.MapPath(folderPath));
                            }
                            var imageName = Path.GetFileName(posted.FileName);
                            imageName = CheckFileName(server, imageName, folderPath);
                            var filePath = folderPath + "/" + imageName;

                            var newImage = new Bitmap(server.MapPath(filePath));
                            int sizeToClip = newImage.Width > newImage.Height ? newImage.Height : newImage.Width;
                            sizeToClip = sizeToClip > 350 ? 350 : sizeToClip;
                            var chunkBounds = new Rectangle(0, 0, sizeToClip, sizeToClip);
                            Bitmap chunk = newImage.Clone(chunkBounds, newImage.PixelFormat);
                            chunk.Save(server.MapPath(filePath), ImageFormat.Jpeg);
                            int sizeThumb = sizeToClip > 150 ? 150 : sizeToClip;
                            Image myThumbnail = chunk.GetThumbnailImage(sizeThumb, sizeThumb, null, IntPtr.Zero);
                            myThumbnail.Save(server.MapPath(filePath));
                            newImage.Dispose();
                            myThumbnail.Dispose();
                            return (new UploadReturn(1, filePath));
                        }
                        else
                        {
                            return (new UploadReturn(2, "Type of file isn't support!Please try another!"));
                        }
                    }
                    else
                    {
                        return (new UploadReturn(3, "ContentLength of File too lagre,please resize picture!"));
                    }
                }
                else
                {
                    return (new UploadReturn(4, "You has not been upload a file!.Please try again!"));
                }

            }

            return (new UploadReturn(5, "You has not been upload a file!.Please try again!"));
        }

        public UploadReturn UploadVideo(System.Web.HttpRequestBase request, System.Web.HttpServerUtilityBase server, string filePath)
        {
            if (request.Files != null)
            {
                var posted = request.Files["uploadFile"];
                if (posted.FileName != "")
                {
                    if (posted.ContentLength < 7501678)
                    {
                        if (posted.ContentType == "video/x-ms-wmv" || posted.ContentType == "video/avi"
                            )
                        {
                            if (!Directory.Exists(server.MapPath(filePath)))
                            {
                                Directory.CreateDirectory(server.MapPath(filePath));
                            }
                            var fileName = CheckFileName(server, Path.GetFileName(posted.FileName), filePath);
                            filePath += "/" + fileName;

                            posted.SaveAs(server.MapPath(filePath));
                            return (new UploadReturn(1, filePath));
                        }
                        else
                        {
                            return (new UploadReturn(2, "Type of file isn't support!Please try another!"));
                        }
                    }
                    else
                    {
                        return (new UploadReturn(3, "ContentLength of File too lagre,please resize picture!"));
                    }
                }
                else
                {
                    return (new UploadReturn(4, "You has not been upload a file!.Please try again!"));
                }

            }

            return (new UploadReturn(5, "You has not been upload a file!.Please try again!"));
        }

        public bool Delete(System.Web.HttpServerUtilityBase server, string filePath)
        {
            if (filePath[0] == '~')
            {
                filePath = filePath.Substring(1, filePath.Length - 1);
            }
            if (System.IO.File.Exists(server.MapPath(filePath)))
            {
                try
                {
                    System.IO.File.Delete(server.MapPath(filePath));
                    return true;
                }
                catch
                {
                    return false;
                }

            }
            return false;
        }

        public bool DeleteFolder(System.Web.HttpServerUtilityBase server, string folderPath)
        {
            if (Directory.Exists(server.MapPath(folderPath)))
            {
                try
                {
                    Directory.Delete(server.MapPath(folderPath), true);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

        public bool MoveFolder(System.Web.HttpServerUtilityBase server, string sourceFolder, string destFolder)
        {
            if (Directory.Exists(server.MapPath(sourceFolder)))
            {
                if (!Directory.Exists(server.MapPath(destFolder)))
                    Directory.CreateDirectory(server.MapPath(destFolder));
                string[] files = System.IO.Directory.GetFiles(server.MapPath(sourceFolder));
                foreach (string s in files)
                {
                    // Use static Path methods to extract only the file name from the path. 
                    var fileName = System.IO.Path.GetFileName(s);
                    var destFile = destFolder + "/" + fileName;
                    try
                    {
                        System.IO.File.Copy(s, server.MapPath(destFile), false);
                    }
                    catch
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        public string GetFileName(string filePath)
        {
            var startIndexOfFileName = filePath.LastIndexOf("/") + 1;
            return filePath.Substring(startIndexOfFileName, filePath.Count() - startIndexOfFileName);
        }

        #region Ultities

        public string CheckFileName(System.Web.HttpServerUtilityBase server, string fileName, string folderPath)
        {
            var filePath = folderPath + "/" + fileName;
            while (System.IO.File.Exists(server.MapPath(filePath)))
            {
                var str = filePath.Substring(filePath.LastIndexOf(".") - 1, 1);
                var checkStr = "012345678";
                if (checkStr.Contains(str))
                {
                    str = (Convert.ToInt32(str) + 1).ToString();
                    filePath =
                        filePath.Substring(0, filePath.LastIndexOf(".") - 1) + str +
                        filePath.Substring(filePath.LastIndexOf("."),
                                           filePath.Length - filePath.LastIndexOf("."));
                }
                else
                {
                    filePath =
                        filePath.Substring(0, filePath.LastIndexOf(".")) + "0" +
                        filePath.Substring(filePath.LastIndexOf("."),
                                           filePath.Length - filePath.LastIndexOf("."));
                }
            }
            var index = filePath.LastIndexOf("/") + 1;
            return filePath.Substring(index);
        }

        public class UploadReturn
        {
            public int Option { get; set; }
            public string ResultString { get; set; }

            public UploadReturn(int _option, string result)
            {
                Option = _option;
                ResultString = result;
            }
        }

        public class FilePathClass
        {
            public FilePathClass(string actionPath, string fileName)
            {
                ActionPath = actionPath;
                FileName = fileName;
            }

            public string ActionPath { get; set; }
            public string FileName { get; set; }
        }
        #endregion

    }
}
